package com.qianlou.service.impl;

import com.qianlou.pojo.vo.EmailVo;
import com.qianlou.service.EmailService;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender mailSender;

    @Override
    public void send(EmailVo emailVo) {
        log.info("开始发送邮件: {}", emailVo.toString());
        try {
            //创建一个MINE消息
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper mineHelper = new MimeMessageHelper(message, true);
            //谁发
            mineHelper.setFrom(from);
            //谁要接收
            List<String> receivers = emailVo.getReceivers();
            String[] to = new String[receivers.size()];
            for (int i = 0; i < receivers.size(); i++) {
                to[i] = receivers.get(i);
            }
            mineHelper.setTo(to);
            //邮件主题
            mineHelper.setSubject(emailVo.getSubject());
            //邮件内容   true 表示带有附件或html
            mineHelper.setText(emailVo.getContent(), true);
            //mailSender.send(message);
        } catch (Exception e) {
            log.info("发送邮件出现异常: {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

}
